package com.banyuan.servlet.opus;


import com.alibaba.fastjson.JSON;
import com.banyuan.dao.OpusDao;
import com.banyuan.domain.Author;
import com.banyuan.domain.Opus;
import com.banyuan.domain.ResData;
import com.banyuan.utils.AuthorUtils;
import com.banyuan.utils.CommonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/opus/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String intro = req.getParameter("intro");
        String typeId = req.getParameter("typeId");
        String icon = req.getParameter("icon");

         // 判断 值 是否为空和""
        if (CommonUtils.isEmpty(name) || CommonUtils.isEmpty(intro) || CommonUtils.isEmpty(typeId) ||
                CommonUtils.isEmpty(icon)) {
            ResData resData = new ResData(10001,"输入项为空",null);
            resp.getWriter().write(JSON.toJSONString(resData));
            return;
        }
        Integer loginId = AuthorUtils.getLoginId(req);
        Opus opus = new Opus();
        opus.setName(name);
        opus.setIntro(intro);
        opus.setIcon(icon);
        opus.setAuthorId(loginId);
        opus.setTypeId(Integer.valueOf(typeId));

        try {
            int insert = OpusDao.insert(opus);
            if (insert > 0) {
                ResData resData = new ResData(200,"添加成功",null);
                resp.getWriter().write(JSON.toJSONString(resData));
            } else {
                ResData resData = new ResData(10002,"添加失败",null);
                resp.getWriter().write(JSON.toJSONString(resData));
            }



        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
